package com.kpx.app.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.kpx.app.R;
import com.kpx.app.adapter.PicAdapter;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.bean.LoginUser;
import com.kpx.app.bean.OrderBean;
import com.kpx.app.bean.OrderDetailBean;
import com.kpx.app.bean.UploadBean;
import com.kpx.app.cache.FileCache;
import com.kpx.app.configs.BroadcastFilters;
import com.kpx.app.configs.Constants;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.ResObj;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.StringUtil;
import com.kpx.app.utils.UIUtils;
import com.kpx.app.utils.UserInfoUtils;
import com.kpx.app.utils.uiutils.IntentUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.view.TitleView;
import com.kpx.app.wigdet.AutoSizeGridView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by congdy on 17/4/16.
 */

public class ActivityOrderUploadPics extends ActivityBase {
    @BindView(R.id.titleview)
    TitleView titleview;
    @BindView(R.id.img_order)
    ImageView imgOrder;
    @BindView(R.id.txt_task_name)
    TextView txtTaskName;
    @BindView(R.id.txt_task_status)
    TextView txtTaskStatus;
    @BindView(R.id.txt_task_ask)
    TextView txtTaskAsk;
    @BindView(R.id.aglist_pics)
    AutoSizeGridView aglistPics;
    @BindView(R.id.btn_up)
    Button btnUp;
    @BindView(R.id.txt_pics)
    TextView txtPics;
    @BindView(R.id.aglist_pics_already)
    AutoSizeGridView aglistPicsAlready;
    @BindView(R.id.ll_pics)
    LinearLayout llPics;
    private OrderBean b;
    private ArrayList<PhotoInfo> list = new ArrayList<PhotoInfo>();
    private ArrayList<PhotoInfo> list2 = new ArrayList<PhotoInfo>();
    private PicAdapter adapter;
    private PicAdapter adapter2;

    @Override
    public void initview(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_order_upload);
        ButterKnife.bind(this);
        UIUtils.setNormalTitle(titleview, "上传图片");
        PhotoInfo add = new PhotoInfo();
        add.setPhotoId(R.drawable.add_pic);
        list.add(add);
        adapter = new PicAdapter(this, list, R.layout.item_pic_show);
        adapter2 = new PicAdapter(this, list2, R.layout.item_pic_show);
        aglistPics.setAdapter(adapter);
        aglistPicsAlready.setAdapter(adapter2);
    }

    @Override
    public void initData() {
        b = (OrderBean) getIntent().getExtras().getSerializable(Constants.KEY_ORDER_BEAN);
        if (b != null) {
            adapter.setOrderBean(b);
            adapter2.setOrderBean(b);
            Glide.with(this).load(b.getTaskGoods().getMainPic()).into(imgOrder);
            txtTaskName.setText(b.getTaskGoods().getGoodsName());
            txtPics.setText("已经上传了" + b.getNowPhotosNum() + "张  请上传"+b.getMinPhotosNum()+"-"+b.getMaxPhotosNum()+"张照片");
            getOrderDetail(b.getDmId());
        }
    }

    /**
     * 获取订单详情
     */
    private void getOrderDetail(long dmid) {
        showLoadingDialog();
        MyHashMap map = new MyHashMap();
        map.put("orderId", dmid + "");
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    OrderDetailBean bd = (OrderDetailBean) result.getData();
                    if (bd != null) {
                        if (bd.getPhotosList() != null && bd.getPhotosList().size() > 0) {
                            llPics.setVisibility(View.VISIBLE);
                            adapter2.setData(bd.getPhotosList());
                            txtPics.setText("已经上传了" + bd.getPhotosList().size() + "张  请上传"+b.getMinPhotosNum()+"-"+b.getMaxPhotosNum()+"张照片");
                        }
                        txtTaskStatus.setText(UIUtils.isEmpty(bd.getPushTypeName()) ? "" : bd.getPushTypeName());
                        txtTaskAsk.setText(UIUtils.isEmpty(bd.getRequirementTxt()) ? "" : bd.getRequirementTxt());
                    }
                } else {
                    ToastUtil.getInstance().showToast(ActivityOrderUploadPics.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog();
                ToastUtil.getInstance().showToast(ActivityOrderUploadPics.this, error);
            }

        }, OrderDetailBean.class, HttpDataRequest.TYPE_OBJECT).POST(HttpDataReqUrl.URL_POST_ORDER_DETAIL, true, map);
    }

    @Override
    public void onReceiver(Context context, Intent intent) {

    }

    public void selectPhoto() {
        requestToCamera(new OnGetCameraPermissionBack() {
            @Override
            public void back() {
                UIUtils.getPhotos(30 - b.getNowPhotosNum(), list, new GalleryFinal.OnHanlderResultCallback() {
                    @Override
                    public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                        if (resultList != null && resultList.size() > 0) {
                            list.clear();
                            PhotoInfo add = new PhotoInfo();
                            add.setPhotoId(R.drawable.add_pic);
                            list.add(add);
                            list.addAll(0, resultList);
                            adapter.setData(list);
                        }
                    }

                    @Override
                    public void onHanlderFailure(int requestCode, String errorMsg) {
                        ToastUtil.getInstance().showToast(ActivityOrderUploadPics.this, errorMsg);
                    }
                });
            }
        });
    }

    @OnClick(R.id.btn_up)
    public void onViewClicked() {
        list.remove(list.size() - 1);
        ArrayList<UploadBean> ulist = new ArrayList<UploadBean>();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        LoginUser loginUser = UserInfoUtils.getCachedLoginUser();
        for (int i = 0; i < list.size(); i++) {
            UploadBean uploadBean = new UploadBean();
            uploadBean.setLocalPath(list.get(i).getPhotoPath());
            uploadBean.setUploadType(UploadBean.TYPE_ORDER_IMG);
            uploadBean.setImageID(System.currentTimeMillis());
            uploadBean.setBindOrderId(b.getDmId() + "");
            uploadBean.setTitleName(b.getTaskGoods().getGoodsName());
            uploadBean.bucketName = UserInfoUtils.getCachedLoginUser().getACCOUNTCONFIG().getBucketone();
            uploadBean.createTime = System.currentTimeMillis();
            String[] date = df.format(new Date()).split("-");
            uploadBean.cloudKey = date[0] + date[1] + "/" + date[2] + "/" + loginUser.getUSER().getDmId() + StringUtil.getUniqueString() + Constants.IMAGE_FILE_SUFFIX;
            ulist.add(uploadBean);
        }
        FileCache.sharedInstance().put(Constants.KEY_UPLOADS_CACHE_LIST, ulist);
        sendBroadcast(new Intent(BroadcastFilters.BROADCAST_ACTION_UPLOAD_ADD_PHOTOS));
        Bundle bundle = new Bundle();
        bundle.putInt("isUpPic", 1);
        IntentUtil.gotoActivityAndFinish(ActivityOrderUploadPics.this, ActivityUploadManager.class, bundle);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public void reFreshUpCount(int size) {
        if (size > 0) {
            llPics.setVisibility(View.VISIBLE);
        } else {
            llPics.setVisibility(View.GONE);
        }
        txtPics.setText("已经上传了" +size + "张  请上传"+b.getMinPhotosNum()+"-"+b.getMaxPhotosNum()+"张照片");
    }
}
